<?php

namespace addons\yunfood\controller;

use addons\yunfood\model\Order;
use think\addons\Controller;

/**
 * 定时任务
 */
class Autotask extends Controller
{
    protected $noNeedLogin = ["*"];
    protected $layout = '';

    public function _initialize()
    {
        parent::_initialize();

        if (! $this->request->isCli()) {
            $this->error('只允许在终端进行操作!');
        }
    }

    /**
     * 自动取消半小时内未支付的订单
     *
     * php public/index.php /addons/yunfood/autotask/handle
     */
    public function handle()
    {
        $timeout = $_SERVER['argv'][2] ?? 1800;
        Order::where('created_at', '<=', time() - $timeout)
            ->where(['status' => Order::STATUS_WAIT_PAY])
            ->chunk(100, function ($orderList) {
                foreach ($orderList as $order) {
                    Order::cancelOrder($order->order_no, Order::STATUS_HAS_TIMEOUT);
                }
            });
    }
}